<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>8-用户名校验</title>
    <style>
        .box{
            width:700px;
            margin:30px auto;
        }
        span.success{
            color: green;
        }
        span.error{
            color:red;
        }
    </style>
</head>
<body>
    <div class="box">
        <input type="text" class="username"><span></span>
    </div>
    <script>
        //只能输入英文字母 数字 下划线 短横线6-16位
        var oInput = document.querySelector('.username');
        var oSpan = document.querySelector('span');
        //失去焦点事件
        oInput.onblur= function(){
            console.log('123');
            //1.数据不能为空校验
            if(this.value==''
            ||this.value==null
            ||this.value==undefined
            ||this.value.length==0){
                //alert('');
                oSpan.innerHTML = '用户名不能为空!';
                oSpan.className = 'error';
                return false;
            }
            //2.正则校验
            var reg = /^[a-zA-Z_-]{6,16}$/;
            if(!reg.test(this.value)){
                oSpan.innerHTML = '用户名英文字母-数字-下划线-短横线6-16位!';
                oSpan.className = 'error';
                return false;
            }
            //3.校验成功
            console.log('success...');
            oSpan.innerHTML = '正确';
            oSpan.className ='success';

        }

    </script>
</body>
</html>